package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.GridView.GridMainActivity;
import com.intelligentmeterreadingsys.util.FileNameUtil;

/**
 * 图片涂鸦
 * 
 * @author king
 * 
 */
public class ScrawlActivity extends Activity {

    private Paint mPaint = null;
    private LinearLayout linear = null;
    private TouchView touchView = null;
    public String classname;
    public String imgpath;
    private Button clearButton = null;
    private Button confirmButton = null;
    private Button cancelButton = null;
    private Button colorview = null;
    private Button[] colorButton = null;
    private Bitmap mbitmap = null;
    private final int colorcount = 7;
    private int COUNT = 0;
    private SeekBar mseekBar = null;
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private int[] colorArray = { Color.YELLOW, Color.BLACK, Color.WHITE, Color.GREEN, Color.GRAY, Color.RED, Color.BLUE };
    DisplayMetrics dm = new DisplayMetrics();
    private String imapepath;// 图片位置
    private String olderImagePath;// 原图片位置
    int screenwidth = 0;
    int screenheight = 0;
    public boolean ismodify = false;
    public int i = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	System.out.println("ScrawlActivity---->OnCreate");
	super.onCreate(savedInstanceState);
	setContentView(R.layout.scrawl);
	classname = getIntent().getStringExtra("classname");
	imgpath = getIntent().getStringExtra("imgpath");
	getWindowManager().getDefaultDisplay().getMetrics(dm);
	screenwidth = (int) (dm.widthPixels);
	screenheight = (int) (dm.heightPixels);
	confirmButton = (Button) findViewById(R.id.confirm);
	cancelButton = (Button) findViewById(R.id.cancel);
	clearButton = (Button) findViewById(R.id.clear);
	linear = (LinearLayout) findViewById(R.id.linear);
	colorButton = new Button[colorcount];
	int[] colorButtonID = { R.id.yellow, R.id.black, R.id.white, R.id.green, R.id.gray, R.id.red, R.id.blue };
	colorview = (Button) findViewById(R.id.color);
	colorview.setBackgroundColor(Color.GREEN);
	for (int i = 0; i < colorcount; i++) {
	    colorButton[i] = (Button) findViewById(colorButtonID[i]);
	    colorButton[i].setBackgroundColor(colorArray[i]);
	}

	mPaint = new Paint();
	mPaint.setAntiAlias(true);
	mPaint.setDither(true);
	mPaint.setColor(Color.GREEN);
	mPaint.setStyle(Paint.Style.STROKE);
	mPaint.setStrokeJoin(Paint.Join.ROUND);
	mPaint.setStrokeCap(Paint.Cap.ROUND);
	mPaint.setStrokeWidth(10);

	mseekBar = (SeekBar) findViewById(R.id.mseekBar);
	mseekBar.setMax(30);
	mseekBar.setProgress(10);
	for (int i = 0; i < colorcount; i++) {
	    colorButton[i].setOnClickListener(new View.OnClickListener() {
		private int colors = colorArray[COUNT];

		public void onClick(View v) {

		    mPaint.setColor(colors);
		    colorview.setBackgroundColor(colors);
		}
	    });
	    COUNT++;
	}
	mseekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
	    @Override
	    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }

	    @Override
	    public void onStartTrackingTouch(SeekBar seekBar) {
		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }

	    @Override
	    public void onStopTrackingTouch(SeekBar seekBar) {

		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }
	});

	confirmButton.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View v) {
		Bitmap bitmap = touchView.mBitmap;
		FileOutputStream out;
		try {

		    out = new FileOutputStream(imapepath);

		    bitmap.getWidth();

		    boolean b = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		    out.flush();
		    out.close();
		    if (b) {
			Toast.makeText(ScrawlActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
		    } else {
			Toast.makeText(ScrawlActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
		    }
		} catch (FileNotFoundException e) {

		    e.printStackTrace();
		} catch (IOException e) {

		    e.printStackTrace();
		}
	    }
	});
	cancelButton.setText("清除");
	cancelButton.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View v) {
		init();
	    }
	});
	clearButton.setText("返回");
	clearButton.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {

		if (classname.equals("OrderImageActivity")) {
		    Intent intent;
		    intent = new Intent(ScrawlActivity.this, OrderImageActivity.class);
		    intent.putExtra("imgpath", imapepath);
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_OK, intent);
		    finish();
		} else if (classname.equals("GridMainActivity")) {
		    Intent intent;
		    intent = new Intent(ScrawlActivity.this, GridMainActivity.class);
		    intent.putExtra("imgpath", imapepath);
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_OK, intent);
		    finish();
		}
	    }
	});
	if (imgpath == null || imgpath.equals("")) {
	    System.out.println(i);
	    ismodify = false;
	    System.out.println("------------------------------拍照");
	    Photograph();
	    i++;
	} else {
	    imapepath = imgpath;
	    ismodify = true;
	    initImage(imapepath, true);
	    init();
	}

    }

    /**
     * 初始化
     */
    public void init() {
	System.out.println("--------------------------5");
	linear.removeAllViews();

	touchView = new TouchView(this);
	// touchView.setScrollContainer(true);

	linear.setPadding((screenwidth - touchView.mBitmap1.getWidth()) / 2, 0, (screenwidth - touchView.mBitmap1.getWidth()) / 2, 0);

	linear.addView(touchView);
    }

    public class TouchView extends View {

	private Bitmap mBitmap;
	private Bitmap mBitmap1;
	private Canvas mCanvas;
	private Path mPath;
	private Paint mBitmapPaint;

	private boolean b = false;

	public TouchView(Context c) {
	    super(c);
	    if (mbitmap == null) {
		return;
	    }
	    mBitmap1 = mbitmap;

	    mBitmap = Bitmap.createBitmap(mBitmap1.getWidth(), mBitmap1.getHeight(), Config.ARGB_8888);
	    mCanvas = new Canvas(mBitmap);
	    mPath = new Path();
	    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

	    mCanvas.drawBitmap(mBitmap1, 0, 0, mBitmapPaint);

	}

	@Override
	protected void onDraw(Canvas canvas) {
	    canvas.drawBitmap(mBitmap1, 0, 0, mBitmapPaint);

	    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

	    canvas.drawPath(mPath, mPaint);

	    // canvas.drawRect(50, 50, 180, 200, mBitmapPaint);

	}

	private float mX, mY;
	private static final float TOUCH_TOLERANCE = 10;

	private void touch_start(float x, float y) {
	    mPath.reset();
	    mPath.moveTo(x, y);
	    mX = x;
	    mY = y;
	}

	private void touch_move(float x, float y) {
	    float dx = Math.abs(x - mX);
	    float dy = Math.abs(y - mY);
	    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
		mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
		mX = x;
		mY = y;
	    }
	}

	private void touch_up() {
	    mPath.lineTo(mX, mY);
	    mCanvas.drawPath(mPath, mPaint);
	    mPath.reset();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
	    float x = event.getX();
	    float y = event.getY();

	    switch (event.getAction()) {
	    case MotionEvent.ACTION_DOWN:
		touch_start(x, y);
		invalidate();
		break;
	    case MotionEvent.ACTION_MOVE:
		touch_move(x, y);
		invalidate();
		break;
	    case MotionEvent.ACTION_UP:
		touch_up();
		invalidate();
		break;
	    }
	    return true;
	}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {

	    if (resultCode == RESULT_OK) {

		initImage(imapepath, false);

	    } else if (resultCode == RESULT_CANCELED) {

		if (classname.equals("OrderImageActivity")) {
		    Intent intent;
		    intent = new Intent(this, OrderImageActivity.class);
		    intent.putExtra("imgpath", "");
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_CANCELED, intent);

		} else if (classname.equals("GridMainActivity")) {
		    Intent intent;
		    intent = new Intent(this, GridMainActivity.class);
		    intent.putExtra("imgpath", "");
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_CANCELED, intent);
		}
		finish();
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 拍照
     */
    public void Photograph() {

	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	FileNameUtil f = new FileNameUtil(this);
	imapepath = f.Orderimgpath();
	if (classname.equals("GridMainActivity")) {
	    imapepath = f.SDCardPath("DaoHang");
	}
	if (imapepath == null) {
	    Toast.makeText(ScrawlActivity.this, "SD卡不可用", Toast.LENGTH_LONG).show();
	    return;
	}
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
	imapepath = imapepath + "/" + fileName;
	olderImagePath = imapepath;

	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imapepath)));
	startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);

    }

    /**
     * 初始化照片
     * 
     * @param imagepath
     * @throws IOException
     */
    public void initImage(String imagepath, boolean b) {

	FileInputStream fis = null;
	try {
	    fis = new FileInputStream(imagepath);

	    FileDescriptor fd = fis.getFD();
	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFileDescriptor(fd, null, options);

	    int outWidth = options.outWidth;
	    int outHeight = options.outHeight;
	    if (b) {
		options.inSampleSize = 1;
	    } else {
		options.inSampleSize = 4;
	    }

	    options.inJustDecodeBounds = false;
	    // 获取这个图片的宽和高

	    // 定义预转换成的图片的宽度和高度

	    int newWidth = 1200;

	    int newHeight = 900;

	    // 计算缩放率，新尺寸除原始尺寸

	    float scaleWidth = ((float) newWidth) / outWidth;

	    float scaleHeight = ((float) newHeight) / outHeight;

	    // 创建操作图片用的matrix对象
	    mbitmap = BitmapFactory.decodeStream(fis, null, options);
	    if (!b) {

		Matrix matrix = new Matrix();
		matrix.setRotate(90);
		// 创建新的图片
		mbitmap = Bitmap.createBitmap(mbitmap, 0, 0, mbitmap.getWidth(), mbitmap.getHeight(), matrix, true);
		FileOutputStream out = new FileOutputStream(imapepath);
		mbitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		out.flush();
		out.close();
		fis.close();
	    }
	    init();
	} catch (FileNotFoundException e) {
	    System.out.println("FileNotFoundException");
	    e.printStackTrace();
	} catch (IOException e) {
	    System.out.println("IOException");
	    e.printStackTrace();
	}

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {

	    if (classname.equals("OrderImageActivity")) {
		Intent intent;
		intent = new Intent(this, OrderImageActivity.class);
		intent.putExtra("imgpath", imapepath);
		intent.putExtra("ismodify", ismodify);
		setResult(RESULT_OK, intent);
	    } else if (classname.equals("GridMainActivity")) {
		Intent intent;
		intent = new Intent(this, GridMainActivity.class);
		intent.putExtra("imgpath", imapepath);
		intent.putExtra("ismodify", ismodify);
		setResult(RESULT_OK, intent);
	    }
	}
	return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {

	if (mbitmap != null) {
	    mbitmap.recycle();
	}
	super.onDestroy();
    }
}